package article_api

import (
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/es_ser"
	"giv-vue-blog/utils/jwts"
)

// ArticleCollCreateView 用户收藏接口
// @Summary 收藏/取消收藏文章
// @Description 用户收藏/取消收藏指定文章
// @Tags 文章管理
// @Accept json
// @Produce json
// @Param data body models.ESIDRequest true "文章ID"
// @Security ApiKeyAuth
// @Success 200 {object} res.Response{}
// @Failure 400 {object} res.Response "参数错误"
// @Failure 401 {object} res.Response "未授权访问"
// @Failure 404 {object} res.Response "文章不存在"
// @Failure 500 {object} res.Response "内部服务器错误"
// @Router /api/articles/collects [post]
func (ArticleApi) ArticleCollCreateView(c *gin.Context) {
	var cr models.ESIDRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailedWithCode(res.ArgumentError, c)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.CustomClaims)
	model, err := es_ser.CommonDetail(cr.ID)
	if err != nil {
		res.FailedWithMsg("文章不存在", c)
		return
	}
	var coll models.UserCollectModel
	err = global.DB.Take(&coll, "user_id=? and article_id=?", claims.UserID, cr.ID).Error
	var num = -1
	if err != nil {
		//没有找到  收藏文章
		global.DB.Create(&models.UserCollectModel{
			UserID:    claims.UserID,
			ArticleID: cr.ID,
		})
		//给文章的收藏数加 1
		num = 1
	}
	//取消收藏
	global.DB.Delete(&coll)
	//文章数减1 更新es中文章收藏数
	_ = es_ser.ArticleUpdateCommon(cr.ID, map[string]any{
		"collects_count": model.CollectsCount + num,
	})
	if num == 1 {
		res.OkWithMsg("收藏成功", c)
	} else {
		res.OkWithMsg("取消收藏成功", c)
	}
}
